# Balance Table
# Creates balance table for match

subtabfun <- function(before_cases, matched_cases, matched_controls, before_controls, match.names){
        
        ######################
        # subtabfun
        # make a balance table
        ######################
                
                #print("check1")
                #print(dim(before_cases))
                #print(dim(matched_cases))
                #print(dim(matched_controls))
                #print(dim(before_controls))
                
                # before_cases$mednum_age <- paste(before_cases$MEDICAL_RECORD_NUMBER, before_cases$ADMIT_AGE_IN_DAYS, sep="")
                # matched_cases$mednum_age <- paste(matched_cases$MEDICAL_RECORD_NUMBER, matched_cases$ADMIT_AGE_IN_DAYS, sep="")
                # matched_controls$mednum_age <- paste(matched_controls$MEDICAL_RECORD_NUMBER, matched_controls$ADMIT_AGE_IN_DAYS, sep="")
                # before_controls$mednum_age <- paste(before_controls$MEDICAL_RECORD_NUMBER, before_controls$ADMIT_AGE_IN_DAYS, sep="")
        
        
                after_id_treat_cases <- matched_cases[,c("newID_8","pair_id")]
                #print(dim(after_id_treat_cases))
                after_id_treat_controls <- matched_controls[,c("newID_8","pair_id")]
                #print(dim(after_id_treat_controls))
                
                #print(table(matched_cases$mednum_age))
                #print(table(before_cases$mednum_age))
                
                before_cases$treat <- rep(1, dim(before_cases)[1])
                before_controls$treat <- rep(0, dim(before_controls)[1])
                
                before_cases <- merge(before_cases, after_id_treat_cases, by="newID_8", all.x=T)
                #before_cases$treat <- rep(1, dim(before_cases)[1])
                #before_cases$treat <- (before_cases$HOSPITAL_NUMBER == hid)*1
                
                
                
                #print(dim(before_cases))
                
                before_controls <- merge(before_controls, after_id_treat_controls, by="newID_8", all.x=T) # appending pair id to identify which controls in the before group ended up being matched
                #before_controls$treat <- rep(0, dim(before_controls)[1])
                #before_controls$treat <- (before_controls$HOSPITAL_NUMBER == hid)*1
                
                #print(dim(before_controls))
                
                #print("check2")
                
                #print(names(before_cases))
                #print(names(before_controls))
                
                # Determine which match.names variables are not binary (but instead continuous)
                cont.names <- NULL
                for (i in 1:length(match.names)){
                        check.var.name <- match.names[i]
                        check.var.data <- subset(before_cases, select=c(check.var.name))
                        
                        if (sum(check.var.data != 0 & check.var.data != 1) > 0) {
                                cont.names <- c(cont.names, check.var.name)
                        }
                }
                
                print(names(before_cases))
                
                before_matrix <- rbind(before_cases[,c(cont.names, match.names[-which(match.names %in% cont.names)], "treatment", "pair_id")], before_controls[,c(match.names, "treatment", "pair_id")])
                after_matrix <- rbind(matched_cases[,c(cont.names, match.names[-which(match.names %in% cont.names)], "treatment", "pair_id")], matched_controls[,c(match.names, "treatment", "pair_id")])
                
                #print(paste("before_matrix",dim(before_matrix)))
                #print(paste("after_matrix",dim(after_matrix)))
                
                #print("check3")
                
                before_data <- as.matrix(subset(before_matrix, select= c(cont.names, match.names[-which(match.names %in% cont.names)])))
                after_data <- as.matrix(subset(after_matrix, select= c(cont.names, match.names[-which(match.names %in% cont.names)])))
                
                #print(summary(before_data))
                #print(summary(after_data))
                #print(dim(before_data))
                #print(dim(after_data))
                
                btest <- rep("f", length(match.names))
                btest[which(match.names %in% cont.names)] <- "w"
                
                #btest <- c(rep("w",5), rep("f",3), rep("w",1), rep("f",1), rep("w",1), rep("f",32), rep("w",2), rep("f",6), rep("w",1) # this is for propensity
                #)
                #print(length(btest))
                
                #print("check4")
                matched_balance <- meantab_both(before_data[,match.names], before_matrix$treat, which(is.na(before_matrix$pair_id)==F & before_matrix$treat == 1), which(is.na(before_matrix$pair_id)==F & before_matrix$treat == 0), exact = btest, digits=4)
                
                before_balance <- meantab_both(before_data[,match.names], before_matrix$treat, which(before_matrix$treat == 1), which(before_matrix$treat==0), exact = btest, digits=4)
                
                #print("check5")
                
                # matching types
                types <- rep(NA, length(rownames(matched_balance)))
                for (t in 1:length(types)){
                        types[t] <- ''
                        if (rownames(matched_balance)[t] %in% c(exact_vars, be.names)){types[t] <- paste(types[t], 'E')}
                        if (rownames(matched_balance)[t] %in% c(cpen.names)){types[t] <- paste(types[t], 'C')}
                        if (rownames(matched_balance)[t] %in% c(pen.names)){types[t] <- paste(types[t], 'P')}
                        if (rownames(matched_balance)[t] %in% mov.names){types[t] <- paste(types[t], 'M')}
                        #if (rownames(matched_balance)[t] %in% colnames(fine_covs)){types[t] <- paste(types[t], 'FB')}
                        if (rownames(matched_balance)[t] %in% c(nf.names,bnf.names)){types[t] <- paste(types[t], 'NF')}
                        #if (rownames(matched_balance)[t] %in% ks.names){types[t] <- paste(types[t], 'KS')}
                        #if (rownames(matched_balance)[t] %in% dist.sometimes.names){types[t] <- paste(types[t], 'D*')}
                        if (rownames(matched_balance)[t] %in% maha_vars){types[t] <- paste(types[t], 'D')}
                        if (types[t] == ''){types[t] <- '.'}
                }
                #types
                
                # Bias Reduction
                #bias_reduction <- (abs(before_balance[,6]) - abs(matched_balance[,6])) / abs(before_balance[,6])
                
                # Caluclating Percent Concordant
                #concord.rates <- concord_miss(after_matrix, after_matrix$treat , after_matrix$pair_id)
                #print(colnames(after_matrix))
                #n.vars <- length(match.names)
                
                #concord_percent <- concord.rates$con.rate[1:n.vars]
                #pos_concord <- concord.rates$pos.rate[1:n.vars]
                #neg_concord <- concord.rates$neg.rate[1:n.vars]
                
                # making table
                balance_table <- cbind(colnames(before_data[,match.names]),types, matched_balance[,8], before_balance[,4], matched_balance[,4], matched_balance[,5], before_balance[,5], before_balance[,6:7], matched_balance[,6:7])
                colnames(balance_table) <- c(1,"Type", "Dev.",paste("All_Cases", dim(before_cases)[1], "(mean)"), paste("Mathced_Cases", dim(matched_cases)[1], "(mean)"), paste("Matched_Controls", dim(matched_controls)[1], "(mean)"), paste("All_Controls", dim(before_controls)[1], "(mean)"), "DIFFAV (B)", "P-value (B)", "DIFFAV (A)", "P-value (A)")
                balance_data_frame <- as.data.frame(balance_table, row.names=FALSE)
                balance_data_frame <- cbind(types, balance_data_frame)
                #print(balance_data_frame)
                
                # number of matched pairs
                total_number_of_matched_pairs <- length(after_matrix[,1])/2
                n_pairs <- paste('Number of matched pairs: ', total_number_of_matched_pairs)
                print(n_pairs)
                
                #jotplot(before_matrix, which(is.na(before_matrix$pair_id)==F & before_matrix$treat == 1), which(is.na(before_matrix$pair_id)==F & before_matrix$treat == 0), 0.1)
                # jotplot(before_data, which(is.na(before_matrix$pair_id)==F & before_matrix$treat == 1), which(is.na(before_matrix$pair_id)==F & before_matrix$treat == 0), 0.1)
                #title(main=paste('Jotplot for Hospital ', hid, sep=""))
                
                #print(balance_table)

                return(balance_table)
}